package cn.ibizlab.eam.core.eam_core.service.impl;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.Map;
import java.util.HashSet;
import java.util.HashMap;
import java.util.Collection;
import java.util.Objects;
import java.util.Optional;
import java.math.BigInteger;

import lombok.extern.slf4j.Slf4j;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cglib.beans.BeanCopier;
import org.springframework.stereotype.Service;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.util.ObjectUtils;
import org.springframework.beans.factory.annotation.Value;
import cn.ibizlab.eam.util.errors.BadRequestAlertException;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.context.annotation.Lazy;
import cn.ibizlab.eam.core.eam_core.domain.EMAsset;
import cn.ibizlab.eam.core.eam_core.filter.EMAssetSearchContext;
import cn.ibizlab.eam.core.eam_core.service.IEMAssetService;

import cn.ibizlab.eam.util.helper.CachedBeanCopier;
import cn.ibizlab.eam.util.helper.DEFieldCacheMap;


import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import cn.ibizlab.eam.core.eam_core.mapper.EMAssetMapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.alibaba.fastjson.JSONObject;
import org.springframework.util.StringUtils;

/**
 * 实体[资产] 服务对象接口实现
 */
@Slf4j
@Service("EMAssetServiceImpl")
public class EMAssetServiceImpl extends ServiceImpl<EMAssetMapper, EMAsset> implements IEMAssetService {

    @Autowired
    @Lazy
    protected cn.ibizlab.eam.core.eam_core.service.IEMAssetClearService emassetclearService;
    @Autowired
    @Lazy
    protected cn.ibizlab.eam.core.eam_core.service.IEMAssetHistService emassethistService;
    @Autowired
    @Lazy
    protected cn.ibizlab.eam.core.eam_core.service.IEMEquipService emequipService;
    @Autowired
    @Lazy
    protected cn.ibizlab.eam.core.eam_core.service.IEMACClassService emacclassService;
    @Autowired
    @Lazy
    protected cn.ibizlab.eam.core.eam_core.service.IEMAssetClassService emassetclassService;
    @Autowired
    @Lazy
    protected cn.ibizlab.eam.core.eam_core.service.IEMEQLocationService emeqlocationService;
    @Autowired
    @Lazy
    protected cn.ibizlab.eam.core.eam_core.service.IEMServiceService emserviceService;
    @Autowired
    @Lazy
    protected cn.ibizlab.eam.core.eam_pf.service.IPFContractService pfcontractService;
    @Autowired
    @Lazy
    protected cn.ibizlab.eam.core.eam_pf.service.IPFUnitService pfunitService;

    protected int batchSize = 500;

    @Override
    @Transactional
    public boolean create(EMAsset et) {
        fillParentData(et);
        if(!this.retBool(this.baseMapper.insert(et))) {
            return false;
        }
        CachedBeanCopier.copy(get(et.getEmassetid()), et);
        return true;
    }

    @Override
    @Transactional
    public void createBatch(List<EMAsset> list) {
        list.forEach(item->fillParentData(item));
        this.saveBatch(list, batchSize);
    }

    @Override
    @Transactional
    public boolean update(EMAsset et) {
        fillParentData(et);
        if(!update(et, (Wrapper) et.getUpdateWrapper(true).eq("emassetid", et.getEmassetid()))) {
            return false;
        }
        CachedBeanCopier.copy(get(et.getEmassetid()), et);
        return true;
    }

    @Override
    @Transactional
    public void updateBatch(List<EMAsset> list) {
        list.forEach(item->fillParentData(item));
        updateBatchById(list, batchSize);
    }

    @Override
    @Transactional
    public boolean remove(String key) {
        boolean result = removeById(key);
        return result ;
    }

    @Override
    @Transactional
    public void removeBatch(Collection<String> idList) {
        removeByIds(idList);
    }

    @Override
    @Transactional
    public EMAsset get(String key) {
        EMAsset et = getById(key);
        if(et == null){
            et = new EMAsset();
            et.setEmassetid(key);
        }
        else {
        }
        return et;
    }

    @Override
    public EMAsset getDraft(EMAsset et) {
        fillParentData(et);
        return et;
    }

    @Override
    public boolean checkKey(EMAsset et) {
        return (!ObjectUtils.isEmpty(et.getEmassetid())) && (!Objects.isNull(this.getById(et.getEmassetid())));
    }
    @Override
    @Transactional
    public boolean save(EMAsset et) {
        if(!saveOrUpdate(et)) {
            return false;
        }
        return true;
    }

    @Override
    @Transactional
    public boolean saveOrUpdate(EMAsset et) {
        if (null == et) {
            return false;
        } else {
            return checkKey(et) ? getProxyService().update(et) : getProxyService().create(et);
        }
    }

    @Override
    @Transactional
    public boolean saveBatch(Collection<EMAsset> list) {
        list.forEach(item->fillParentData(item));
        List<EMAsset> create = new ArrayList<>();
        List<EMAsset> update = new ArrayList<>();
        for (EMAsset et : list) {
            if (ObjectUtils.isEmpty(et.getEmassetid()) || ObjectUtils.isEmpty(getById(et.getEmassetid()))) {
                create.add(et);
            } else {
                update.add(et);
            }
        }
        if (create.size() > 0) {
            getProxyService().createBatch(create);
        }
        if (update.size() > 0) {
            getProxyService().updateBatch(update);
        }
        return true;
    }

    @Override
    @Transactional
    public void saveBatch(List<EMAsset> list) {
        list.forEach(item->fillParentData(item));
        List<EMAsset> create = new ArrayList<>();
        List<EMAsset> update = new ArrayList<>();
        for (EMAsset et : list) {
            if (ObjectUtils.isEmpty(et.getEmassetid()) || ObjectUtils.isEmpty(getById(et.getEmassetid()))) {
                create.add(et);
            } else {
                update.add(et);
            }
        }
        if (create.size() > 0) {
            getProxyService().createBatch(create);
        }
        if (update.size() > 0) {
            getProxyService().updateBatch(update);
        }
    }


	@Override
    public List<EMAsset> selectByAcclassid(String emacclassid) {
        return baseMapper.selectByAcclassid(emacclassid);
    }
    @Override
    public void removeByAcclassid(String emacclassid) {
        this.remove(new QueryWrapper<EMAsset>().eq("acclassid",emacclassid));
    }

	@Override
    public List<EMAsset> selectByAssetclassid(String emassetclassid) {
        return baseMapper.selectByAssetclassid(emassetclassid);
    }
    @Override
    public void removeByAssetclassid(String emassetclassid) {
        this.remove(new QueryWrapper<EMAsset>().eq("assetclassid",emassetclassid));
    }

	@Override
    public List<EMAsset> selectByEqlocationid(String emeqlocationid) {
        return baseMapper.selectByEqlocationid(emeqlocationid);
    }
    @Override
    public void removeByEqlocationid(String emeqlocationid) {
        this.remove(new QueryWrapper<EMAsset>().eq("eqlocationid",emeqlocationid));
    }

	@Override
    public List<EMAsset> selectByLabserviceid(String emserviceid) {
        return baseMapper.selectByLabserviceid(emserviceid);
    }
    @Override
    public void removeByLabserviceid(String emserviceid) {
        this.remove(new QueryWrapper<EMAsset>().eq("labserviceid",emserviceid));
    }

	@Override
    public List<EMAsset> selectByMserviceid(String emserviceid) {
        return baseMapper.selectByMserviceid(emserviceid);
    }
    @Override
    public void removeByMserviceid(String emserviceid) {
        this.remove(new QueryWrapper<EMAsset>().eq("mserviceid",emserviceid));
    }

	@Override
    public List<EMAsset> selectByRserviceid(String emserviceid) {
        return baseMapper.selectByRserviceid(emserviceid);
    }
    @Override
    public void removeByRserviceid(String emserviceid) {
        this.remove(new QueryWrapper<EMAsset>().eq("rserviceid",emserviceid));
    }

	@Override
    public List<EMAsset> selectByContractid(String pfcontractid) {
        return baseMapper.selectByContractid(pfcontractid);
    }
    @Override
    public void removeByContractid(String pfcontractid) {
        this.remove(new QueryWrapper<EMAsset>().eq("contractid",pfcontractid));
    }

	@Override
    public List<EMAsset> selectByUnitid(String pfunitid) {
        return baseMapper.selectByUnitid(pfunitid);
    }
    @Override
    public void removeByUnitid(String pfunitid) {
        this.remove(new QueryWrapper<EMAsset>().eq("unitid",pfunitid));
    }


    /**
     * 查询集合 报废资产
     */
    @Override
    public Page<EMAsset> searchAssetBf(EMAssetSearchContext context) {
        com.baomidou.mybatisplus.extension.plugins.pagination.Page<EMAsset> pages=baseMapper.searchAssetBf(context.getPages(),context,context.getSelectCond());
        return new PageImpl<EMAsset>(pages.getRecords(), context.getPageable(), pages.getTotal());
    }

    /**
     * 查询集合 DEFAULT
     */
    @Override
    public Page<EMAsset> searchDefault(EMAssetSearchContext context) {
        com.baomidou.mybatisplus.extension.plugins.pagination.Page<EMAsset> pages=baseMapper.searchDefault(context.getPages(),context,context.getSelectCond());
        return new PageImpl<EMAsset>(pages.getRecords(), context.getPageable(), pages.getTotal());
    }



    /**
     * 为当前实体填充父数据（外键值文本、外键值附加数据）
     * @param et
     */
    private void fillParentData(EMAsset et){
        //实体关系[DER1N_EMASSET_EMACCLASS_ACCLASSID]
        if(!ObjectUtils.isEmpty(et.getAcclassid())){
            cn.ibizlab.eam.core.eam_core.domain.EMACClass acclass=et.getAcclass();
            if(ObjectUtils.isEmpty(acclass)){
                cn.ibizlab.eam.core.eam_core.domain.EMACClass majorEntity=emacclassService.get(et.getAcclassid());
                et.setAcclass(majorEntity);
                acclass=majorEntity;
            }
            et.setAcclassname(acclass.getEmacclassname());
        }
        //实体关系[DER1N_EMASSET_EMASSETCLASS_ASSETCLASSID]
        if(!ObjectUtils.isEmpty(et.getAssetclassid())){
            cn.ibizlab.eam.core.eam_core.domain.EMAssetClass assetclass=et.getAssetclass();
            if(ObjectUtils.isEmpty(assetclass)){
                cn.ibizlab.eam.core.eam_core.domain.EMAssetClass majorEntity=emassetclassService.get(et.getAssetclassid());
                et.setAssetclass(majorEntity);
                assetclass=majorEntity;
            }
            et.setAssetclassname(assetclass.getEmassetclassname());
            et.setAssetclasscode(assetclass.getAssetclasscode());
        }
        //实体关系[DER1N_EMASSET_EMEQLOCATION_EQLOCATIONID]
        if(!ObjectUtils.isEmpty(et.getEqlocationid())){
            cn.ibizlab.eam.core.eam_core.domain.EMEQLocation eqlocation=et.getEqlocation();
            if(ObjectUtils.isEmpty(eqlocation)){
                cn.ibizlab.eam.core.eam_core.domain.EMEQLocation majorEntity=emeqlocationService.get(et.getEqlocationid());
                et.setEqlocation(majorEntity);
                eqlocation=majorEntity;
            }
            et.setEqlocationname(eqlocation.getEqlocationinfo());
        }
        //实体关系[DER1N_EMASSET_EMSERVICE_LABSERVICEID]
        if(!ObjectUtils.isEmpty(et.getLabserviceid())){
            cn.ibizlab.eam.core.eam_core.domain.EMService labservice=et.getLabservice();
            if(ObjectUtils.isEmpty(labservice)){
                cn.ibizlab.eam.core.eam_core.domain.EMService majorEntity=emserviceService.get(et.getLabserviceid());
                et.setLabservice(majorEntity);
                labservice=majorEntity;
            }
            et.setLabservicename(labservice.getEmservicename());
        }
        //实体关系[DER1N_EMASSET_EMSERVICE_MSERVICEID]
        if(!ObjectUtils.isEmpty(et.getMserviceid())){
            cn.ibizlab.eam.core.eam_core.domain.EMService mservice=et.getMservice();
            if(ObjectUtils.isEmpty(mservice)){
                cn.ibizlab.eam.core.eam_core.domain.EMService majorEntity=emserviceService.get(et.getMserviceid());
                et.setMservice(majorEntity);
                mservice=majorEntity;
            }
            et.setMservicename(mservice.getEmservicename());
        }
        //实体关系[DER1N_EMASSET_EMSERVICE_RSERVICEID]
        if(!ObjectUtils.isEmpty(et.getRserviceid())){
            cn.ibizlab.eam.core.eam_core.domain.EMService rservice=et.getRservice();
            if(ObjectUtils.isEmpty(rservice)){
                cn.ibizlab.eam.core.eam_core.domain.EMService majorEntity=emserviceService.get(et.getRserviceid());
                et.setRservice(majorEntity);
                rservice=majorEntity;
            }
            et.setRservicename(rservice.getEmservicename());
        }
        //实体关系[DER1N_EMASSET_PFCONTRACT_CONTRACTID]
        if(!ObjectUtils.isEmpty(et.getContractid())){
            cn.ibizlab.eam.core.eam_pf.domain.PFContract contract=et.getContract();
            if(ObjectUtils.isEmpty(contract)){
                cn.ibizlab.eam.core.eam_pf.domain.PFContract majorEntity=pfcontractService.get(et.getContractid());
                et.setContract(majorEntity);
                contract=majorEntity;
            }
            et.setContractname(contract.getPfcontractname());
        }
        //实体关系[DER1N_EMASSET_PFUNIT_UNITID]
        if(!ObjectUtils.isEmpty(et.getUnitid())){
            cn.ibizlab.eam.core.eam_pf.domain.PFUnit unit=et.getUnit();
            if(ObjectUtils.isEmpty(unit)){
                cn.ibizlab.eam.core.eam_pf.domain.PFUnit majorEntity=pfunitService.get(et.getUnitid());
                et.setUnit(majorEntity);
                unit=majorEntity;
            }
            et.setUnitname(unit.getPfunitname());
        }
    }




    @Override
    public List<JSONObject> select(String sql, Map param){
        return this.baseMapper.selectBySQL(sql,param);
    }

    @Override
    @Transactional
    public boolean execute(String sql , Map param){
        if (sql == null || sql.isEmpty()) {
            return false;
        }
        if (sql.toLowerCase().trim().startsWith("insert")) {
            return this.baseMapper.insertBySQL(sql,param);
        }
        if (sql.toLowerCase().trim().startsWith("update")) {
            return this.baseMapper.updateBySQL(sql,param);
        }
        if (sql.toLowerCase().trim().startsWith("delete")) {
            return this.baseMapper.deleteBySQL(sql,param);
        }
        log.warn("暂未支持的SQL语法");
        return true;
    }

    @Override
    public List<EMAsset> getEmassetByIds(List<String> ids) {
         return this.listByIds(ids);
    }

    @Override
    public List<EMAsset> getEmassetByEntities(List<EMAsset> entities) {
        List ids =new ArrayList();
        for(EMAsset entity : entities){
            Serializable id=entity.getEmassetid();
            if(!ObjectUtils.isEmpty(id)){
                ids.add(id);
            }
        }
        if(ids.size()>0) {
            return this.listByIds(ids);
        }
        else {
            return entities;
        }
    }


    public IEMAssetService getProxyService() {
        return cn.ibizlab.eam.util.security.SpringContextHolder.getBean(this.getClass());
    }
}



